package test29.Lambda;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;

/*
 * Java8 内置的四大核心函数式接口
 * Consumer<T> : 消费型接口
 * 		void accept(T t);
 *
 * Supplier<T> : 供给型接口
 * 		T get();
 *
 * Function<T, R> : 函数型接口
 * 		R apply(T t);
 *
 * Predicate<T> : 断言型接口
 * 		boolean test(T t);
 *
 */
public class LambdaTest2 {
    //Consumer<T> 消费型接口 :
    @Test
    public void test1(){
        happy(500, new Consumer<Double>() {
            @Override
            public void accept(Double aDouble) {
                System.out.println("学习太累，奖励自己买可乐，价格为:"+aDouble);
            }
        });

        happy(10000, money -> System.out.println("学习太累，奖励自己买可乐，价格为：" + money + "元"));
    }
    public void happy(double money, Consumer<Double> con){
        con.accept(money);
    }

    @Test
    public void test2(){
        List<String> list = Arrays.asList("北京","南京","天津","东京","西京");
        List<String> filterStrs = filterString(list, new Predicate<String>() {
            @Override
            public boolean test(String s) {
                return s.contains("京");
            }
        });
        System.out.println(filterStrs);//[北京, 南京, 东京, 西京]

        System.out.println("==============");
        List<String> filterString = filterString(list, s -> s.contains("京"));
        System.out.println(filterString);

    }
    //根据给定的规则，过滤集合中的字符串，此规则有Predicate的方法决定
    public List<String> filterString(List<String> list, Predicate<String> predicate){
        ArrayList<String> filterList = new ArrayList<>();
        for (String s : list){
            if (predicate.test(s)){
                filterList.add(s);
            }
        }
        return filterList;
    }
}
